package com.mate.cloud.auth.controller;


import com.mate.cloud.auth.param.LoginUserParam;
import com.mate.cloud.auth.utils.JwtUtil;
import com.mate.cloud.common.response.BaseResponse;
import com.mate.cloud.common.web.controller.AdminBaseController;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 *  视图控制器
 * @author:         MI
 * @email:          448341911@qq.com
 * @createTime:     2025/6/5 18:54
 * @updateUser:     MI
 * @updateTime:     2025/6/5 18:54
 * @updateRemark:   修改内容
 * @version:        1.0
 */
@Slf4j
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class LoginController extends AdminBaseController {


    private final UserDetailsService userDetailsService;

    private final AuthenticationManager authenticationManager;
    // 处理GET请求
    @PostMapping("/login")
    public BaseResponse login(@RequestBody LoginUserParam loginUserParam) {
        log.info("login user: {}", loginUserParam);
//        UserDetails userDetails = userDetailsService.loadUserByUsername(loginUserParam.getUserName());
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(loginUserParam.getUserName(), loginUserParam.getPassWord());
        Authentication authentication = authenticationManager.authenticate(auth);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        //用户身份验证成功，生成并返回jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", userDetails.getUsername());


        String jwtToken = JwtUtil.generateToken(userDetails.getUsername());
//        String jwtToken = JwtUtil.createJwt(null,(1000 * 60 * 60 * 4),claims);

        return successBodyResponse(jwtToken);
    }


}
